package com.lobaby.tools.modules.pdf.service.impl;

import cn.hutool.core.io.FileUtil;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.lobaby.tools.common.utils.DateUtils;
import com.lobaby.tools.common.utils.PdfUtils;
import com.lobaby.tools.common.utils.StringUtil;
import com.lobaby.tools.common.utils.UploadUtil;
import com.lobaby.tools.model.ConsoleResult;
import com.lobaby.tools.modules.pdf.service.IPdfService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Stream;

/**
 * @author Administrator
 *         Created by Administrator on 2021/3/1 0001.
 */
@Service
public class PdfServiceImpl implements IPdfService {
    private static final Logger LOGGER = LoggerFactory.getLogger(PdfServiceImpl.class);

    @Override
    public ConsoleResult pdftopng(MultipartFile file) throws Exception {
        if (file != null) {
            File resoureDir = StringUtil.getCurrentJarPathFile(PdfServiceImpl.class, "/resource/pdf/");

            File targetPath = new File(resoureDir, StringUtil.getFileName(file.getOriginalFilename()) + "_"
                    + DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_YYYYMMDDHHMMSS));
            if (!targetPath.exists()) {
                targetPath.mkdirs();
            }

            List<String> paths = PdfUtils.convertToPic(file.getInputStream(),
                    StringUtil.getFileName(file.getOriginalFilename()), targetPath.getAbsolutePath());
            ConsoleResult result = ConsoleResult.getSuccessObj("成功！");
            result.setObject(paths.get(0));
            return result;
        } else {
            return ConsoleResult.getErrObj("获取文件失败，请稍后重试！");
        }
    }

    @Override
    public ConsoleResult wordtopdf(MultipartFile file) throws Exception {
        if (file != null) {
            File resoureDir = StringUtil.getCurrentJarPathFile(PdfServiceImpl.class, "/resource/pdf/");

            String targetPath = StringUtil.getFileName(file.getOriginalFilename()) + "_"
                    + DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_YYYYMMDDSSS) + ".pdf";
            File target = new File(resoureDir, targetPath);
            OutputStream os = new FileOutputStream(target);

            Document document = new Document(file.getInputStream());
            document.save(os, SaveFormat.PDF);
            os.flush();
            os.close();
            ConsoleResult result = ConsoleResult.getSuccessObj("成功！");
            result.setObject(target.getAbsolutePath());
            return result;
        } else {
            return ConsoleResult.getErrObj("获取文件失败，请稍后重试！");
        }
    }

    @Override
    public ConsoleResult picToPdf(List<MultipartFile> files) throws Exception {
        File tempDir = StringUtil.getCurrentJarPathFile(PdfServiceImpl.class, "/resource/_temp/");

        // 复制文件到临时目录
        files.stream().forEach(x -> {
            try {
                File targetFile = new File(tempDir, x.getOriginalFilename());
                UploadUtil.writeFile(targetFile, x.getInputStream());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        File pdfDir = StringUtil.getCurrentJarPathFile(PdfServiceImpl.class, "/resource/pdf/");

        String targetFileName = StringUtil.getFileName(files.get(0).getOriginalFilename()) + ".pdf";
        File targetFile = new File(pdfDir, targetFileName);
        PdfUtils.picToPdf(tempDir.getAbsolutePath(), targetFile.getAbsolutePath());

        UploadUtil.delFileDir(tempDir.getAbsolutePath());
        ConsoleResult result = ConsoleResult.getSuccessObj("成功！");
        result.setObject(targetFile.getAbsolutePath());
        return result;
    }

    @Override
    public ConsoleResult pdfmerge(List<MultipartFile> files) throws Exception {
        File tempDir = StringUtil.getCurrentJarPathFile(PdfServiceImpl.class, "/resource/_temp/");

        // 获取 pdf 文件目录
        File pdfDir = StringUtil.getCurrentJarPathFile(PdfServiceImpl.class, "/resource/pdf/");

        // 目标文件名和目标文件
        String targetFileName = StringUtil.getFileName(files.get(0).getOriginalFilename()) + ".pdf";
        File targetFile = new File(pdfDir, targetFileName);

        // 将现有的 pdf 转成图片，放在临时目录中
        File tempPicDir = new File(tempDir, DateUtils.formatDate(new Date(), "yyyyMMddHHmmSS"));
        if (!tempPicDir.exists()) {
            tempPicDir.mkdirs();
        }
        List<String> picPaths = new ArrayList<>();
        files.stream().forEach(x -> {
            try {
                List<String> picPath = PdfUtils.convertToPic(x.getInputStream(), StringUtil.getFileName(x.getOriginalFilename()), tempPicDir.getAbsolutePath());
                picPaths.addAll(picPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        PdfUtils.picToPdf(tempPicDir.getAbsolutePath(), targetFile.getAbsolutePath());

        UploadUtil.delFileDir(tempPicDir.getAbsolutePath());
        ConsoleResult result = ConsoleResult.getSuccessObj("成功！");
        result.setObject(targetFile.getAbsolutePath());
        return result;
    }

    @Override
    public ConsoleResult pdfsplit(List<MultipartFile> files, Map<String, String> requestParam) {
        if (files.size() > 1 || files.size() <= 0) {
            return ConsoleResult.getErrObj("只能上传一个 pdf 文件");
        }
        MultipartFile multipartFile = files.get(0);
        File tempDir = StringUtil.getCurrentJarPathFile(PdfServiceImpl.class, "/resource/_temp/");
        if (!tempDir.exists()) {
            tempDir.mkdirs();
        }
        File tempPicDir = new File(tempDir, DateUtils.formatDate(new Date(), "yyyyMMddHHmmSS"));
        if (!tempPicDir.exists()) {
            tempPicDir.mkdirs();
        }
        // 获取 pdf 文件目录
        File pdfDir = StringUtil.getCurrentJarPathFile(PdfServiceImpl.class, "/resource/pdf/");
        if (!pdfDir.exists()) {
            tempDir.mkdirs();
        }
        File splitPdfPath = new File(pdfDir, DateUtils.formatDate(new Date(), "yyyyMMddHHmmSS"));
        if (!splitPdfPath.exists()) {
            splitPdfPath.mkdirs();
        }
        // 将 pdf 转成图片
        List<String> picPaths = new ArrayList<>();
        try {
            List<String> picPath = PdfUtils.convertToPic(multipartFile.getInputStream(), StringUtil.getFileName(multipartFile.getOriginalFilename()),
                    tempPicDir.getAbsolutePath());
            picPaths.addAll(picPath);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String start = requestParam.get("start");
            if (!StringUtil.isBlank(start)) {
                if (start.contains("，")) {
                    start = start.replaceAll("，", ",");
                }
                String[] split = start.split(",");
                Stream.of(split).forEach(x -> {
                    String[] splitNum = x.split("-");
                    Integer splitStart = Integer.parseInt(splitNum[0]);
                    splitStart--;
                    if (splitStart < 0) {
                        splitStart = 0;
                    }
                    Integer splitEnd = Integer.parseInt(splitNum[1]);
                    File currentGroup = new File(tempPicDir, x);
                    if (!currentGroup.exists()) {
                        currentGroup.mkdirs();
                    }
                    picPaths.subList(splitStart, splitEnd).stream().forEach(y -> {
                        String fileName = y.substring(y.lastIndexOf("\\") + 1, y.length());
                        FileUtil.copy(new File(y), new File(currentGroup, fileName), true);
                    });

                    File targetFile = new File(splitPdfPath, x + ".pdf");
                    try {
                        PdfUtils.picToPdf(currentGroup.getAbsolutePath(), targetFile.getAbsolutePath());
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                });
            } else {
                // 按页拆分
                picPaths.stream().forEach(x -> {
                    try {
                        String pdfName = x.substring(x.lastIndexOf("\\") + 1, x.length());
                        File targetFile = new File(splitPdfPath, pdfName + ".pdf");
                        PdfUtils.picToPdf(x, targetFile.getAbsolutePath());
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                });
            }

        } catch (Exception e) {
            return ConsoleResult.getErrObj("拆分页数有误，请重新输入");
        }

        UploadUtil.delFileDir(tempPicDir.getAbsolutePath());
        ConsoleResult result = ConsoleResult.getSuccessObj("成功！");
        result.setObject(splitPdfPath.getAbsolutePath());
        return result;
    }
}